package edu.mercer.sse.tasks.math;

import java.util.Random;

import com.google.common.base.Function;

/**
 * 
 * Estimate Pi using Monte Carlo method.<p>
 * 
 * Perform guesses as part of Monte Carlo method Pi approximation.<p>
 *
 *<ul>
 * <li>Accepts number of guesses; i.e., attempts.
 * 
 * <li>Returns number of hits; i.e., successes.
 *</ul>
 *
 * @see Function
 */

public class EstimatePiFunction implements Function<Double,Double>
{
	private static final Double CIRCLE_RADIUS = 1d;
	
	@Override
	public Double apply( final Double tosses )
	{
		return estimatePi( tosses );
		
	}//method
	

	private Double estimatePi( final Double tosses )
	{
		double hits = 0d;
		
		double xCoordinate = 0d;
		double yCoordinate = 0d;

		for (double dartsTossed = 0d; dartsTossed < tosses; 
				dartsTossed++) 
		{
			
			xCoordinate = CIRCLE_RADIUS * ( new Random().nextDouble() );
			yCoordinate = CIRCLE_RADIUS * ( new Random().nextDouble() );
			
			if ( Math.sqrt( Math.pow(xCoordinate,2) 
					
			   + Math.pow( yCoordinate, 2 ) )
					
				 <= 
					
				 Math.pow( CIRCLE_RADIUS, 2 )
			   )
			{
				hits++;

			}//if
			
			if (Thread.interrupted())                  
			{
				Thread.currentThread().interrupt();
		        throw new RuntimeException("thread interrupted");
		        
		    }//if
			
		}//for
		
		return hits;
		
	}//method
	

}//class
